package cn.cdutetc.foxwatch.interceptors;

import cn.cdutetc.foxwatch.exception.MyException;
import cn.cdutetc.foxwatch.utils.JwtUtil;
import cn.cdutetc.foxwatch.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

//拦截器
@Component
public class LoginInterceptor implements HandlerInterceptor {
    //每次发送请求过来验证token，成功就将获取的解析数据放入ThreadLocal中，，访问结束，就清除
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //令牌验证
        String token = request.getHeader("Authorization");
        //暂时不拦截请求
        try {
            Map<String, Object> claims = JwtUtil.parseToken(token);//返回值是map
            //放行
            ThreadLocalUtil.set(claims);
            return true;
        } catch (Exception e) {
            System.out.println("身份证验证失败.....");
<<<<<<< HEAD
            response.setStatus(401);
=======
//            response.setStatus(401);
            e.printStackTrace();
>>>>>>> f0dd41dd48d79067fa2de22e427243c250479df2
            //不放行
            throw new MyException(500, "身份证验证失败");
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}